<template>
  <div class="app-container">
    <el-alert :closable="false" :title="title" />
    <el-form
      ref="articleForm"
      :model="articleForm"
      :rules="rules"
      label-width="60px"
      label-position="left"
      class="demo-ruleForm"
      style="margin-top: 20px"
      :validate-on-rule-change="false"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="标题" prop="title" required>
            <el-input v-model="articleForm.title" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="描述" prop="desc">
            <el-input v-model="articleForm.desc" type="textarea" :rows="5" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="6">
          <el-form-item label="状态" prop="status">
            <el-select v-model="articleForm.status" placeholder="请选择文章状态">
              <el-option v-for="(item, index) in statusData" :key="index" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="用户" prop="userId">
            <el-select v-model="articleForm.userId" placeholder="请选择操作人">
              <el-option v-for="(item, index) in adminData" :key="index" :label="item.nickname" :value="item.id"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="分类" prop="typeId">
            <el-select v-model="articleForm.typeId" placeholder="请选择文章分类">
              <el-option v-for="(item, index) in classList" :key="index" :label="item.className" :value="item.id"/>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item label="标签" prop="tagId">
            <el-select v-model="articleForm.tagId" placeholder="请选择文章标签" >
              <el-option v-for="(item, index) in tagList" :key="index" :label="item.tagName" :value="item.id"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="20">
          <el-form-item label="封面" prop="coverImg" required>
            <el-input
              v-model="articleForm.coverImg"
              placeholder="请填写封面图片链接或者上传一张图片作为封面"
            />
          </el-form-item>
        </el-col>
        <el-col :span="3" :offset="1">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="afterUpload"
          >
            <el-button type="text">上传封面图片</el-button>
          </el-upload>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="11" :style="{ paddingLeft: '60px', marginBottom: '20px' }">
          <img v-if="articleForm.coverImg" :src="articleForm.coverImg" class="cover" />
        </el-col>
      </el-row>

      <el-row>
        <el-col v-loading="loading" :span="24">
          <el-form-item label="内容" prop="content">
            <mavonEditor
              v-model="articleForm.content"
              :style="{ 'min-height': '700px' }"
              @change="mdChange"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item>
            <el-button type="primary" @click="updateArticle('articleForm')"> 立即发布 </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import { mavonEditor } from "mavon-editor";
import "mavon-editor/dist/css/index.css";
import { getAllAdmin } from "@/api/user";
import { getAllClass } from "@/api/classIfy";
import { addEditArticle, getDetail } from "@/api/article";
import { getTagList } from "@/api/tags"
import { getArticle } from "@/api/reptiles";
export default {
  components: { mavonEditor },
  data() {
    return {
      classList: [],
      adminData: [],
      tagList: [],
      loading: false,
      articleForm: {
        title: null,
        typeId: null,
        desc: null,
        status: null,
        userId: null,
        tagId: null,
        content: null,
        coverImg: null,
        html: null
      },
      rules: {
        title: [{ required: true, message: "请输入文章标题", trigger: "blur" }],
        desc: [{ required: true, message: "请输入详细描述", trigger: "blur" }],
        coverImg: [{ required: true, message: "请使用一张图片作为封面", trigger: "blur" }],
        typeId: [{ required: true, message: "请选择文章分类", trigger: "change" }],
        status: [{ required: true, message: "请选择状态", trigger: "change" }],
        userId: [{ required: true, message: "请选择用户", trigger: "change" }],
        content: [{ required: true, message: "请填写文章内容", trigger: "blur" }]
      },
      statusData: [{ name: "草稿", id: 0 },{ name: "已发布", id: 1 }]
    };
  },
  computed: {
    title: function() {
      return (this.$route.params.url || this.$route.query.id) ? "编辑文章" : "新增文章"
    },
    uploadUrl() {
      return process.env.VUE_APP_UPLOAD_URL;
    }
  },

  created() {
    this.getAllClass();
    this.getTagList()
    this.isEdit();
    this.getAllAdmin();
    this.addArticle();
  },
  methods: {
    mdChange(value, render) {
      this.articleForm.html = render;
    },
    // 上传文章
    updateArticle(ruleForm) {
      this.$refs[ruleForm].validate((valid) => {
        if (valid) {
          this.$confirm(`是否上传文章 "${this.articleForm.title}"`, "提示", {
            confirmButtonText: "确定", cancelButtonText: "取消", type: "success"
          }).then(async() => {
            const data = Object.assign(this.articleForm, { id: this.$route.query.id });
            const res = await addEditArticle(data);
            res.code === 1 && this.$message({ type: "success", message: res.msg });
            res.code === 1 && this.$router.push("/file/manageFile");
          });
        }
      });
    },
    async getAllClass() {
      const result = await getAllClass();
      this.classList = result.data;
    },
    async getTagList() {
      const res = await getTagList({pageSize:200})
      this.tagList = res.data.rows
    },
    afterUpload(res) {
      this.$message({ type: "success", message: res.msg });
      this.articleForm.coverImg = res.data[0].url;
      res.code === 1 && (this.articleForm.coverImg = res.data[0].url);
    },
    async isEdit() {
      if (this.$route.query.id) {
        const result = await getDetail({ id: this.$route.query.id });
        const { title, typeId, desc, status, userId, content, coverImg, html, tagId } = result.data
        Object.assign(this.articleForm, { title, typeId, desc, status, userId, content, coverImg, html, tagId })
      }
    },
    async getAllAdmin() {
      const result = await getAllAdmin();
      this.adminData = result.data;
    },
    async addArticle() {
      if (this.$route.params.url) {
        this.loading = true;
        const result = await getArticle({
          url: this.$route.params.url,
          type: this.$route.params.type || 1,
        });
        this.loading = false;
        this.articleForm.content = result.data;
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.cover {
  width: 50%;
  border: 1px dashed #ccc;
  border-radius: 5px;
}
</style>
